package com.zlzlib.libui.util;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import androidx.core.content.FileProvider;

import java.io.File;
import java.util.List;


/**
 * Created by zlz on 2018/6/7.
 * 一些系统方法
 */
public class AppSystemUtil {

    /**
     * @return 版本名称
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception ignored) {
        }
        return versionName;
    }

    /**
     * @return 版本号
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (Exception ignored) {
        }
        return verCode;
    }

    /**
     * 复制文字到剪切板
     *
     * @param txt 文字
     */
    public static void copyTextB(Context context, String txt) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", txt);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * @param key data键值
     * @return 获取manifest 的data值
     */
    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return "";
        }
        String channelNumber = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelNumber = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelNumber;
    }


    /**
     * 隐藏键盘
     */
    public static void dismissKeyboard(Activity activity) {
        try {
            ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception ignored) {
        }
    }

    /**
     * 弹出键盘
     */
    public static void showKeyboard(Context context) {
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception ignored) {
        }
    }

    /**
     * 安装APK文件
     * 8.0需要处理未知应用来源权限问题
     * <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
     */
    public static void installApk(File file, Context context) {
        if (file == null || !file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 通过Intent安装APK文件
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, context.getPackageName(), file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static void addShortcut(Context context, String activityName, int nameId, int iconId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), iconId, null);
        addShortcut(context, activityName, null, context.getResources().getString(nameId), bitmap);
    }

    public static void addShortcut(Context context, String activityName, String name, int iconId) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), iconId, null);
        addShortcut(context, activityName, null, name, bitmap);
    }

    /**
     * 添加桌面图标快捷方式
     * <!--快捷方式-->
     * <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" /><!-- 添加快捷方式 -->
     * <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /><!-- 移除快捷方式 -->
     * <uses-permission android:name="android.permission.INSTALL_SHORTCUT" />
     * <uses-permission android:name="android.permission.UNINSTALL_SHORTCUT" />
     * <!-- 查询快捷方式2.1以下 -->
     * <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
     * <uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
     * <!-- 查询快捷方式4.4及以下 -->
     * <uses-permission android:name="com.android.launcher2.permission.READ_SETTINGS" />
     * <uses-permission android:name="com.android.launcher2.permission.WRITE_SETTINGS" />
     * <!-- 查询快捷方式4.4以上 -->
     * <uses-permission android:name="com.android.launcher3.permission.READ_SETTINGS" />
     * <uses-permission android:name="com.android.launcher3.permission.WRITE_SETTINGS" />
     *
     * @param activityName 点击弹出的页面名称  全名
     * @param bundle       打开页面传输的数据
     * @param name         快捷方式名称
     * @param icon         快捷方式图标
     */
    public static void addShortcut(Context context, String activityName, Bundle bundle, String name, Bitmap icon) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            addShortcutOld(context, activityName, bundle, name, icon);
        } else {
            addShortcutNew(context, activityName, bundle, name, icon);
        }
    }

    public static void addShortcutNew(Context context, String activityName, Bundle bundle, String name, Bitmap icon) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Intent shortcutIntent = new Intent();
            shortcutIntent.setAction(Intent.ACTION_VIEW);
            //设置点击快捷方式，进入指定的Activity
            //注意：因为是从Lanucher中启动，所以这里用到了ComponentName
            //其中new ComponentName这里的第二个参数，是Activity的全路径名，也就是包名类名要写全。
            shortcutIntent.putExtra("bundleShortcut", bundle);
            shortcutIntent.setComponent(new ComponentName(context.getPackageName(), activityName));
            //给Intent添加 对应的flag
            shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
            ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
            boolean requestPinShortcutSupported = shortcutManager.isRequestPinShortcutSupported();
            if (requestPinShortcutSupported) {
                ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(context, name)
                        .setShortLabel(name).setLongLabel(name).setIcon(Icon.createWithBitmap(icon))
                        .setIntent(shortcutIntent).build();
                //当添加快捷方式的确认弹框弹出来时，将被回调
                Intent pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(shortcutInfo);
                PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast
                        (context, 0, pinnedShortcutCallbackIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                shortcutManager.requestPinShortcut(shortcutInfo, shortcutCallbackIntent.getIntentSender());
            }
        }
    }

    public static void addShortcutOld(Context context, String activityName, Bundle bundle, String name, Bitmap icon) {
        Intent shortcutIntent = new Intent();
        shortcutIntent.setAction(Intent.ACTION_VIEW);
        //设置点击快捷方式，进入指定的Activity
        //注意：因为是从Lanucher中启动，所以这里用到了ComponentName
        //其中new ComponentName这里的第二个参数，是Activity的全路径名，也就是包名类名要写全。
        shortcutIntent.putExtra("bundleShortcut", bundle);
        shortcutIntent.setComponent(new ComponentName(context.getPackageName(), activityName));
        //给Intent添加 对应的flag
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
        //  创建快捷方式的intent广播
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 添加快捷名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
        //  快捷图标是否允许重复(不一定有效)
        shortcut.putExtra("duplicate", false);
        // 快捷图标
        // 使用资源id方式
//            Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(activity, R.mipmap.icon);
//            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        // 使用Bitmap对象模式
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
        // 添加携带的下次启动要用的Intent信息
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        // 发送广播
        context.sendBroadcast(shortcut);
    }


    /**
     * @param context 上下文
     * @param title   快捷方式标志，不能和其它应用相同
     * @return 快捷方式是否存在
     */
    public static boolean isShortCutExist(Context context, String title) {
        boolean isInstallShortcut = false;
        if (null == context || TextUtils.isEmpty(title))
            return false;
        String authority = getAuthority();
        final ContentResolver cr = context.getContentResolver();
        if (!TextUtils.isEmpty(authority)) {
            try {
                final Uri CONTENT_URI = Uri.parse(authority);
                Cursor c = cr.query(CONTENT_URI, new String[]{"title", "iconResource"},
                        "title=?", new String[]{title.trim()}, null);
                // XXX表示应用名称。
                if (c != null && c.getCount() > 0) {
                    isInstallShortcut = true;
                }
                if (null != c && !c.isClosed()) c.close();
            } catch (Exception ignored) {
            }
        }
        return isInstallShortcut;
    }

    private static String getAuthority() {
        String authority;
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
            authority = "com.android.launcher.settings";
        } else if (sdkInt <= 19) {// Android 4.4及以下
            authority = "com.android.launcher2.settings";
        } else {// 4.4以上
            authority = "com.android.launcher3.settings";
        }
        return "content://" + authority + "/favorites?notify=true";
    }


    /**
     * 启动某个app
     *
     * @param packageName app的包名
     */
    public static void startApp(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return;
        }
        if (pi == null) {
            return;
        }
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pi.packageName);
        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName(packageName, className);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    /**
     * 启动其它app的service
     * 后台启动
     *
     * @param intent      传递的数据
     * @param pagePack    包名
     * @param serviceName 名称
     * @return 是否启动成功
     */
    public static boolean startOtherService(Context context, Intent intent, String pagePack, String serviceName) {
        try {
            ComponentName componentName = new ComponentName(pagePack, serviceName);
            intent.setComponent(componentName);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 创建一个通知栏
     *
     * @param id        唯一标识
     * @param title     显示的标题
     * @param content   显示的内容
     * @param cls       点击后跳转的页面
     * @param smallIcon 图标
     * @param soundUri  出现播放的声音  为null为静音
     * @return 通知栏
     */
    public static Notification getNotification(Context context, String id, String title, String content, Class<?> cls, int smallIcon, Uri soundUri) {
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            /**
             * 该channel通知的重要程度
             * NotificationManager.IMPORTANCE_MIN: 静默;
             * NotificationManager.IMPORTANCE_HIGH:随系统使用声音或振动
             */
            NotificationChannel channel = new NotificationChannel(id, title,
                    soundUri == null ? NotificationManager.IMPORTANCE_MIN : NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
            //设置通知声音
            if (soundUri != null) {
                AudioAttributes att = new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
                channel.setSound(soundUri, att);
            }
            builder = new Notification.Builder(context.getApplicationContext(), id);
            builder.setChannelId(id);
        } else {
            builder = new Notification.Builder(context.getApplicationContext());
        }
        Intent nfIntent = new Intent(context, cls);
        builder.setContentIntent(PendingIntent.getActivity(context, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE))
                .setContentTitle(title) // 设置下拉列表里的标题
                .setSmallIcon(smallIcon) // 设置状态栏内的小图标
                .setContentText(content) // 设置上下文内容
                .setWhen(System.currentTimeMillis())// 设置该通知发生的时间
                .setSound(soundUri); //设置通知声音
        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_VIBRATE; //设置默认的响铃方式为震动
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        return notification;
    }
}
